package control;

import java.util.ArrayList;
import server.mysqlConnection;




/**
 * @author Shay
 *
 *
 *   This class responsible for the operation Watch Reader Card, when the client wants to activate this operation he inserts data in the GUI client
,the data we insert into array string that will send to the server, In the server we maps the message by checking the first string (see AbstractControl).*/


public class WatchReaderCardControl extends AbstractControl
{


	private String checkSid;
	private String[][] resultSubscriberInfo;
	private String[][] resultBooksrInfo;
	
	public WatchReaderCardControl()
	{
		
	}
	
	@Override
	public  Object anlyze(String[] msg) 
	{
		checkSid=msg[1];
		ArrayList<Object> returnMsg=new ArrayList<Object>();
		if(checkExist() )
		{
			returnMsg.add("watchRedearCard");
			returnMsg.add(resultSubscriberInfo);
			subscriberBooks();
			returnMsg.add(resultBooksrInfo);
			String query1 = new String("SELECT date,log FROM logs WHERE sid=" +msg[1]+" order by date desc;");
			String[][] actions=mysqlConnection.select(query1, 2);
			returnMsg.add(actions);
			return returnMsg;
		}
		returnMsg.add("watchRedearCard No Such Subscriber!!");
		return returnMsg;
	}
	
	



	/* (non-Javadoc)
	 * @see control.AbstractControl#checkExist()
	 * //We check if this subscriber is exist in DB
	 */
	@Override
	public Boolean checkExist()
	{
		String key=new String("Select FirstName,LastName,Phone,email,CardStatus from users,subscriber WHERE users.ID=subscriber.sid and users.ID="+checkSid);
		resultSubscriberInfo=mysqlConnection.select(key,5);
		if(resultSubscriberInfo.length>0)
		{
			return true;
		}
		return false;
	}
	
	
	
	/**
	 * //We need to send back a message to the client with a matrix string (table) which contains the whole books of the subscriber
	 */
	private void subscriberBooks()
	{
		String key=new String("Select bid,copy,borrowDate,expectedReturnDate,incident,returnDate from borrow WHERE sid=" +checkSid);
		String[][] midRst=mysqlConnection.select(key,6);
		String[][] rstFromSql;
		resultBooksrInfo=new String[midRst.length][9];
		for(int i=0;i<midRst.length;i++)
		{
			for(int j=0;j<6;j++)
			{
				resultBooksrInfo[i][j]=midRst[i][j];
			}
		}
		System.out.println(resultBooksrInfo.toString());
		for(int i=0;i<midRst.length;i++)
		{
			String query=new String("Select Name,author,ispopular"+" from books WHERE bid="+midRst[i][0]+" and copy="+midRst[i][1]);
			rstFromSql=mysqlConnection.select(query,3);
			for(int j=0;j<3;j++)
			{
				resultBooksrInfo[i][6+j]=rstFromSql[0][j];
			}
		}
	}
	
	

}
